import {useState, useEffect, useCallback, useRef} from 'react'
import {Row, Col, Input, List, Typography, Button, Icon, Tag, Menu, Dropdown, Modal, message, Upload, Card} from 'antd';
import {
    LeftCircleOutlined,
    PlusCircleOutlined,
    SettingOutlined,
    UploadOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import Link from 'next/link'
import dynamic from 'next/dynamic';
import {withRouter} from 'next/router'
import MarkdownIt from 'markdown-it'
import 'react-markdown-editor-lite/lib/index.css';
import service from '../../lib/service';

const MdEditor = dynamic(() => import('react-markdown-editor-lite'), {
    ssr: false
});
const mdParser = new MarkdownIt();
const { confirm } = Modal;
const ArticleEditor = (props) => {
    const [article, setArticle] = useState({
        content: "",
        articleTitle: ""
    })
    const [articleList, setArticleList] = useState([])
    // const [title, setTitle] = useState('')
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [classify, setClassify] = useState('');
    const [classifyList, setClassifyList] = useState([]);
    const [classifyId, setClassifyId] = useState(0);//判断弹窗是执行修改还是添加
    const [token, setToken] = useState('');

    useEffect(() => {
        getClassify();
    }, [])

    const handleImageUpload = async (file) => {
        console.log(file)
        try {
            const result = await service.uploadFile(file);
            console.log(result)
            let data = result.data.data;
            console.log(data);
            message.success('添加图片成功');
            return data;
        } catch {
            message.error('添加图片失败');
        }
    }

    const menu = (
        <Menu>
            <Menu.Item>
                <a target="_blank" rel="noopener noreferrer" onClick={(e) => {
                    console.log(e)
                    setIsModalVisible(true)
                }}>
                    修改文集
                </a>
            </Menu.Item>
            <Menu.Item>
                <a target="_blank" rel="noopener noreferrer" onClick={() => {
                    showConfirm();
                }}>
                    删除文集
                </a>
            </Menu.Item>
        </Menu>
    );
    const handleOk = async () => {
        if (classifyId != 0) {
            updateClassify();
        } else {
            addClassify();
        }
        setIsModalVisible(false);
        setClassifyId(0)
        setClassify('')
    };
    const getClassify = async () => {
        try {
            const result = await service.getClassify();
            let data = result.data.data;
            console.log(data);
            setClassifyList(data);
        } catch {
            message.error('获取用户文集失败');
        }
    }

    const showConfirm = () =>  {
        confirm({
            title: '你确定要删除吗',
            icon: <ExclamationCircleOutlined />,
            content: '删除后数据不可恢复',
            onOk() {
                console.log('OK');
                showConfirmAgain();
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    const showConfirmAgain = () =>  {
        confirm({
            title: '再次确认一下，你确定要删除吗',
            icon: <ExclamationCircleOutlined />,
            content: '删除后数据不可恢复，并且所有文章都会被消失',
            onOk() {
                console.log('OK');
                deleteClassify();
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    const deleteClassify = async () => {
        try {
            let data = {
                tid: classifyId
            }
            const result = await service.deleteClassify(data);
            console.log(result)
            message.success('删除用户文集成功');
            getClassify()
        } catch {
            message.error('删除用户文集失败');
        }
    }
    const addClassify = async () => {
        try {
            let data = {
                tagName: classify
            }
            const result = await service.addClassify(data);
            console.log(result)
            if (result.data.success == true) {
                message.success('添加用户文集成功');
                getClassify()
            }
        } catch {
            message.error('添加用户文集失败');
        }
    }
    const updateArticle = async () => {
        try {
            let data = {
                ...article
            }
            const result = await service.updateArticle(data);
            console.log(result)
            if (result.data.success == true) {
                message.success('修改文章成功');
            }
        } catch {
            message.error('修改文章失败');
        }
    }
    const updateClassify = async () => {
        try {
            let data = {
                newTagName: classify,
                tid: classifyId
            }
            const result = await service.updateClassify(data);
            console.log(result)
            if (result.data.success == true) {
                message.success('修改用户文集成功');
                getClassify()
            }
        } catch {
            message.error('修改用户文集失败');
        }
    }
    const addArticle = async () => {
        try {
            //articleImg
            let data = {
                tid: article.tid,
                title: article.articleTitle,
                content: article.content
            }
            const result = await service.addArticle(data);
            console.log(result);
            if (result.data.success == true) {
                message.success('添加文章成功');
            }
        } catch {
            message.error('添加文章失败');
        }
    }
    const getArticle = async (id) => {
        try {
            let data = {
                tid: id,
                page: 1,
                limit: 100
            }
            const result = await service.getArticle(data);
            console.log(result)
            let d = result.data.data.records;
            console.log(d)
            setArticleList([...d])
            setClassifyId(id)
            console.log(articleList)
        } catch {
            message.error('查看文章失败');
        }
    }
    const getArticleDetail = async (id) => {
        let aid = id
        try {
            let data = {
                aid
            }
            const result = await service.getArticleDetail(data);
            console.log(result)
            const {articleTitle,content,id,markId,uid} = result.data.data
            setArticle({articleTitle,content,id,markId,uid})
        } catch {
            message.error('查看文章详情失败');
        }
    }
    const add = () => {
        let d = [{
            tid: classifyId,
            articleTitle: "请输入标题"
        },...articleList]
        setArticleList(d)
    }
    function handleEditorChange({html, text}) {
        console.log('handleEditorChange', html, text)
        article.content = text;
        setArticle({...article})
    }

    function submit() {
        console.log(article);
        if(article.id){
            updateArticle();
        }else{
            addArticle();
        }

    }

    const onChange = (e) => {
        console.log(e)
    }

    return (
        <>
            <Row style={{height: "100%"}}>
                <Col span={4}>
                    <div className="header clear">
                        <Link href={`/index`}>
                            <Button icon={<LeftCircleOutlined/>} className="lf">
                                回首页
                            </Button>
                        </Link>

                        <Button icon={<PlusCircleOutlined/>} className="rf" type="primary"
                                onClick={() => {
                                    setClassifyId(0);
                                    setIsModalVisible(true)
                                }}>
                            添加文集
                        </Button>
                    </div>
                    <List
                        bordered
                        dataSource={classifyList}
                        renderItem={(item,index) => (
                            <div key={index}>
                                <List.Item>
                                    <Typography.Text onClick={() => {
                                        setClassifyId(item.id);
                                        getArticle(item.id)
                                    }}>{item.tagName}</Typography.Text>
                                    <Dropdown overlay={menu}>
                                        <SettingOutlined onClick={e => {
                                            e.preventDefault();
                                            setClassifyId(item.id);
                                        }}
                                        />
                                    </Dropdown>
                                </List.Item>

                            </div>
                        )}
                    />
                </Col>
                <Col span={4}>
                    <div className="header clear">
                        <Button icon={<PlusCircleOutlined/>} className="rf" type="primary"
                                onClick={() => {
                                    add();
                                }}>
                            添加文章
                        </Button>
                    </div>
                    <List
                        bordered
                        dataSource={articleList}
                        renderItem={item => (
                            <>
                                <List.Item>
                                    <Typography.Text onClick={() => {
                                        if(item.id){
                                            console.log(item.id)
                                            getArticleDetail(item.id)
                                        }else{
                                            setArticle(item)
                                        }

                                    }}>{item.articleTitle}</Typography.Text>
                                </List.Item>
                                {/*<Dropdown overlay={menu}>*/}
                                    {/*<SettingOutlined onClick={e => {*/}
                                        {/*e.preventDefault();*/}
                                        {/*setClassifyId(item.id);*/}
                                    {/*}}*/}
                                    {/*/>*/}
                                {/*</Dropdown>*/}
                            </>
                        )}
                    />
                </Col>
                <Col span={16} className="editor-layout" style={{height: "100%"}}>
                    <div className="title clear">
                        <Input placeholder="标题" className="name lf" value={article.articleTitle} onChange={(e) => {
                            article.articleTitle = e.target.value
                            setArticle({...article})
                        }}/>
                        <Button type="primary" className="rf" onClick={submit}>发布</Button>
                    </div>
                    <MdEditor
                        style={{height: "100%"}}
                        value={article.content}
                        config={{
                            view: {
                                menu: true,
                                md: true,
                                html: true,
                                fullScreen: true,
                                hideMenu: true,
                            },
                            table: {
                                maxRow: 5,
                                maxCol: 6,
                            },
                            imageUrl: 'https://octodex.github.com/images/minion.png',
                            syncScrollMode: ['leftFollowRight', 'rightFollowLeft'],
                        }}
                        renderHTML={(text) => mdParser.render(text)}
                        onChange={handleEditorChange}
                        onImageUpload={handleImageUpload}
                    />
                </Col>
            </Row>
            <Modal title="请输入文集名" visible={isModalVisible} onOk={handleOk} onCancel={() => {
                setIsModalVisible(false)
            }}>
                <Input placeholder="文集名" onChange={(e) => {
                    setClassify(e.target.value)
                }}/>
            </Modal>
            <style jsx global>
                {`
                body{
                    height: 100%;
                }
                #__next{
                    height: 100%;
                }
                .header{
                    padding: 12px;
                }
                .clear{
                    overflow: hidden;
                }
                .lf{
                    float: left;
                }
                .rf{
                    float: right;
                }
                .editor-layout{

                }
                .title{
                    display: flex;
                    align-items: center;
                    height: 57px;
                }
                .name{
                     flex: 1
                     height: 50px;
                     border-radius: 0;
                     border: none;
                }
                .ant-list-bordered{
                    border-radius: 0;
                }
                `}
            </style>
        </>
    )
}
ArticleEditor.getInitialProps = async (context) => {
    console.log(context);
}
export default withRouter(ArticleEditor)